package com.gdpu.project.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gdpu.page.vo.QueryResult;
import com.gdpu.project.dao.CgProjectDao;
import com.gdpu.project.vo.CgConference;
import com.gdpu.project.vo.CgPatent;
import com.gdpu.project.vo.CgProject;
import com.gdpu.project.vo.CgThesis;
import com.gdpu.project.vo.Teacher;

/**
 * A data access object (DAO) providing persistence and search support for
 * CgProject entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.gdpu.project.vo.CgProject
 * @author MyEclipse Persistence Tools
 */

public class CgProjectDaoImpl extends HibernateDaoSupport implements CgProjectDao {
	private static final Log log = LogFactory.getLog(CgProjectDaoImpl.class);
	// property constants
	public static final String PROJECT_ID = "projectId";
	public static final String PROJECT_NAME = "projectName";
	public static final String TEACHER_ID = "teacherId";
	public static final String PROJECT_TYPE = "projectType";
	public static final String PROJECT_ORIGIN = "projectOrigin";
	public static final String PROJECT_XZ = "projectXz";
	public static final String RESEARCH_TYPE = "researchType";
	public static final String FU_ZE_REN = "fuZeRen";
	public static final String KE_YAN_FEN = "keYanFen";
	public static final String COMMENT = "comment";

	protected void initDao() {
		// do nothing
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#save(com.gdpu.project.vo.CgProject)
	 */
	public void save(CgProject transientInstance) {
		log.debug("saving CgProject instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#delete(com.gdpu.project.vo.CgProject)
	 */
	public void delete(CgProject persistentInstance) {
		log.debug("deleting CgProject instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findById(java.lang.Integer)
	 */
	public CgProject findById(java.lang.Integer id) {
		log.debug("getting CgProject instance with id: " + id);
		try {
			CgProject instance = (CgProject) getHibernateTemplate().get(
					"com.gdpu.project.vo.CgProject", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByExample(com.gdpu.project.vo.CgProject)
	 */
	public QueryResult<CgProject> findByExample(CgProject instance,int firstindex,int maxresult) {
		log.debug("finding CgProject instance by example");
		try {
			QueryResult<CgProject> queryResult=new QueryResult<CgProject>();
			List<CgProject> results = getHibernateTemplate().findByExample(instance).subList(firstindex, firstindex+maxresult-1);
			log.debug("find by example successful, result size: "
					+ results.size());
			queryResult.setResultlist(results);
			int count= getHibernateTemplate().findByExample(instance).size();
			queryResult.setTotalrecord(count);
			return queryResult;
				
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByProperty(java.lang.String, java.lang.Object)
	 */
	
	//根据teacherId来查找cgproject的方法
	public QueryResult<CgProject> findByProperty(String propertyName, Object value,int firstindex,int maxresult) {
		/*log.debug("finding CgProject instance with property: " + propertyName
				+ ", value: " + value);*/
		try {
			Query query1=getSessionFactory().getCurrentSession().createQuery("from CgProject as model where model."+ propertyName + " like :propertyName");
			Query query2=getSessionFactory().getCurrentSession().createQuery(" select count(*) from CgProject as model where model."+ propertyName + " like :propertyName");
			if(value!=null){
				query1.setParameter("propertyName",value,Hibernate.STRING);
				query2.setParameter("propertyName",value);
			}else{
				query1.setParameter("propertyName", "%%");
				query2.setParameter("propertyName", "%%");
			}
			if(firstindex!=-1&&maxresult!=-1){
				query1.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			QueryResult<CgProject> queryResult=new QueryResult<CgProject>();
			queryResult.setResultlist(query1.list());
			queryResult.setTotalrecord((Long)query2.uniqueResult());
			/*value !=null?query.setParameter(propertyName, value):query.setParameter(propertyName, "%%");*/
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	public List<CgProject> nfindByProperty(String propertyName, String value,Date begin,Date end) {
		/*log.debug("finding CgProject instance with property: " + propertyName
				+ ", value: " + value);*/
		try {
			StringBuilder builder=new StringBuilder();
			String queryString = "from CgProject as model where model."
				+ propertyName + "= ?";
			builder.append(queryString);
			if(begin!=null){
				builder.append(" and model.projApproTime>=? ");
			}
			if(end!=null){
				builder.append(" and model.projApproTime<=? ");
			}
			List<Object> pramList=new ArrayList<Object>();
			if(value!=null){
				pramList.add(value);
			}
			if(begin!=null){
				pramList.add(begin);
			}
			if(end!=null){
				pramList.add(end);
			}
			
			return (List<CgProject>)getHibernateTemplate().find(builder.toString(), pramList.toArray());
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	public QueryResult<CgProject> nfindByProperty(String propertyName, List value,Date begin,Date end,int firstindex,int maxresult) {
		log.debug("finding CgProject instance with property: " + propertyName
				+ ", value: " + value.toString());
		
		try {
			QueryResult<CgProject> queryResult=new QueryResult<CgProject>();
			//String val[]=(String[])value.toArray();
			StringBuffer queryStr=new StringBuffer();
			queryStr.append("from CgProject as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.projApproTime>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.projApproTime<:end");
			}
			Query query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(begin!=null){
				query.setParameter("begin", begin);
			}
			if(end!=null){
				query.setParameter("end", end);
			}
			if(firstindex!=-1&&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			if(value.size()>0){
				queryResult.setResultlist(query.list());
			}
			queryStr.delete(0,queryStr.length());//清除之前的字符窜
			queryStr.append("select count(*) from CgProject as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.projApproTime>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.projApproTime<:end");
			}
			query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(query.getQueryString().indexOf(" and model.projApproTime>=:begin")!=-1){
				query.setParameter("begin", begin);
			}
			if(query.getQueryString().indexOf(" and model.projApproTime<:end")!=-1){
				query.setParameter("end", end);
			}
			if(value.size()>0){
				queryResult.setTotalrecord((Long)query.uniqueResult());
			}
			
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	
	/*public List<CgProject> findByProperty(String propertyName, Object value) {
		List<CgProject> list=(List<CgProject>)getHibernateTemplate().find("from CgProject as c where c."+propertyName+"=?",value);
		return list;
	}*/

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByProjectId(java.lang.Object)
	 */
	public QueryResult<CgProject> findByProjectId(Object projectId,int firstindex,int maxresult) {
		return findByProperty(PROJECT_ID, projectId,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByProjectName(java.lang.Object)
	 */
	public QueryResult<CgProject> findByProjectName(Object projectName,int firstindex,int maxresult) {
		return findByProperty(PROJECT_NAME, projectName,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByTeacherId(java.lang.Object)
	 */
	
	
	
	//根据teacherID来查找，关联到上面的方法
	public QueryResult<CgProject> findByTeacherId(Object teacherId,int firstindex,int maxresult) {
		return findByProperty(TEACHER_ID, teacherId,firstindex,maxresult);
	}
	public QueryResult<CgProject> findByTeacherId(Object teacherId) {
		return findByProperty(TEACHER_ID, teacherId,-1,-1);
	}
	
	
	
	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByProjectType(java.lang.Object)
	 */
	public QueryResult<CgProject> findByProjectType(Object projectType,int firstindex,int maxresult) {
		return findByProperty(PROJECT_TYPE, projectType,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByProjectOrigin(java.lang.Object)
	 */
	public QueryResult<CgProject> findByProjectOrigin(Object projectOrigin,int firstindex,int maxresult) {
		return findByProperty(PROJECT_ORIGIN, projectOrigin,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByProjectXz(java.lang.Object)
	 */
	public QueryResult<CgProject> findByProjectXz(Object projectXz,int firstindex,int maxresult) {
		return findByProperty(PROJECT_XZ, projectXz, firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByResearchType(java.lang.Object)
	 */
	public QueryResult<CgProject> findByResearchType(Object researchType,int firstindex,int maxresult) {
		return findByProperty(RESEARCH_TYPE, researchType,firstindex, maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByFuZeRen(java.lang.Object)
	 */
	public QueryResult<CgProject> findByFuZeRen(Object fuZeRen,int firstindex,int maxresult) {
		return findByProperty(FU_ZE_REN, fuZeRen,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByKeYanFen(java.lang.Object)
	 */
	public QueryResult<CgProject> findByKeYanFen(Object keYanFen,int firstindex,int maxresult) {
		return findByProperty(KE_YAN_FEN, keYanFen,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findByComment(java.lang.Object)
	 */
	public QueryResult<CgProject> findByComment(Object comment,int firstindex,int maxresult) {
		return findByProperty(COMMENT, comment,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#findAll()
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<CgProject> findAll(int firstindex,int maxresult) {
		log.debug("finding all CgProject instances");
		try {
			QueryResult<CgProject> queryResult=new QueryResult<CgProject>();
			Query query=getSessionFactory().getCurrentSession().createQuery("from CgProject cgProject");
			if(firstindex!=-1&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			queryResult.setResultlist(query.list());
			query=getSessionFactory().getCurrentSession().createQuery("select count(*) from CgProject cgProject");
			queryResult.setTotalrecord((Long)query.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#merge(com.gdpu.project.vo.CgProject)
	 */
	public CgProject merge(CgProject detachedInstance) {
		log.debug("merging CgProject instance");
		try {
			CgProject result = (CgProject) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#attachDirty(com.gdpu.project.vo.CgProject)
	 */
	public void attachDirty(CgProject instance) {
		log.debug("attaching dirty CgProject instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.vo.CgProjectDao#attachClean(com.gdpu.project.vo.CgProject)
	 */
	public void attachClean(CgProject instance) {
		log.debug("attaching clean CgProject instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CgProjectDao getFromApplicationContext(ApplicationContext ctx) {
		return (CgProjectDao) ctx.getBean("CgProjectDAO");
	}

	public int count(String teacherId) {
		String hql="from CgProject as c where c.teacherId=?";
		int count=0;
		List<CgProject> list=(List<CgProject>)getHibernateTemplate().find(hql, teacherId);
		Iterator<CgProject> cgproject=list.iterator();
		while(cgproject.hasNext())
		{
			CgProject c=cgproject.next();
			if(c.getKeYanFen()==0f){
				count=count+0;
			}else{
				count=count+(int)c.getKeYanFen();
			}
		}
		return count;
	}

	@Override
	public QueryResult<CgProject> findAll() {
		
		return findAll(-1,-1);
	}

	
}